﻿/*
   Copyright 2012 University of Southampton

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace uk.ac.soton.ses
{
    public class HDCWatcherQueueItem_FolderCheckQuick : HDCWatcherQueueItem
    {
        protected bool _quickCheck = true;

        protected HDCPath _hdcPath = null;

        public HDCPath HDCPath { get { return this._hdcPath; } }

        public HDCWatcherQueueItem_FolderCheckQuick(string path, HDCFileSystemWatcher fileSystemWatcher)
            : base(fileSystemWatcher)
        {
            this._hdcPath = new HDCPath(path, base._fileSystemWatcher.WatchFolder, base._fileSystemWatcher.BasePathDepthInWatchFolder);
            this._quickCheck = true;
        }

        override protected void SetKey()
        {
            if (string.IsNullOrEmpty(this._hdcPath.BasePath))
            {
                this._key = this._hdcPath.FullPath;
            }
            else
            {
                this._key = this._hdcPath.BasePath;
            }
        }

        override public bool IsValid()
        {
            HDCPath hdcPath = this._hdcPath;
            //We will ignore top level files
            if (hdcPath.PathType == PathType.File && hdcPath.RemainingPath.Length == 0)
            {
                string message = string.Format("File created at top level, outside containing folder, ignoring {0}", hdcPath.FullPath);
                HDCFileSystemWatcher.Message(message, TraceLevel.Info);
                return false;
            }

            if (hdcPath.PathType == PathType.Unknown && hdcPath.BasePath.Length == 0 && hdcPath.RemainingPath.Length == 0)
            {
                string message = "File deleted at level higher than we care about. Ignoring.";
                HDCFileSystemWatcher.Message(message, TraceLevel.Info);
                return false;
            }

            if (hdcPath.PathType == PathType.Unknown && hdcPath.BasePath.Length > 0 && hdcPath.RemainingPath.Length == 0)
            {
                string message = "File deleted at top level, not possible to process. Triggering folder checking to clear up deleted folders.";
                HDCFileSystemWatcher.Message(message, TraceLevel.Warning);
                HDCWatcherQueueProcessing.QueueMetadataCheck(base._fileSystemWatcher);
                return false;
            }

            //Ignoring activity outside experiment folders (such as creation of user directory, or something else in watched folder)
            if (hdcPath.BasePath.Length == 0)
            {
                string message = string.Format("File activity outside an experiment, ignoring {0}", hdcPath.FullPath);
                HDCFileSystemWatcher.Message(message, TraceLevel.Info);
                return false;
            }

            //We will ignore certain names
            string[] remainingPathComponents = hdcPath.RemainingPath.Split(Path.DirectorySeparatorChar);
            if (remainingPathComponents[0].Equals(base._fileSystemWatcher.TrackingFileParent, StringComparison.OrdinalIgnoreCase) || base._fileSystemWatcher.FileNamesToIgnore.Contains(hdcPath.ObjectName, StringComparer.OrdinalIgnoreCase))//.Any(ign =>hdcPath.ObjectName.Equals(ign, StringComparison.OrdinalIgnoreCase)))
            {
                string message = string.Format("{0} is a name we ignore", hdcPath.RemainingPath);
                HDCFileSystemWatcher.Message(message, TraceLevel.Info);
                return false;
            }

            //Check whether it's a directory lower down (a non empty file name would indicate it was not an experiment)
            if (hdcPath.PathType == PathType.Folder && hdcPath.RemainingPath.Length > 0)
            {
                string message = "Empty sub directories are not interesting to us here, only new experiment folders";
                HDCFileSystemWatcher.Message(message, TraceLevel.Info);
                return false;
            }

            return true;
        }

        public override void DoWork()
        {
            this.CheckFolder();
        }

        protected void CheckFolder()
        {
            HDCWatcherFolderCheck folderCheckData = new HDCWatcherFolderCheck(this, this._quickCheck);
            folderCheckData.FindAndProcessChanges();

            //Hopefully finished
            //HDCFileSystemWatcher.Message(string.Format("{0} finished", this.HDCPath.FullPath), ConsoleColor.DarkYellow);
        }
    }

}
